package main.api;

import com.mongodb.client.AggregateIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.result.DeleteResult;
import main.*;
import main.database.*;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.ObjectId;
import org.json.JSONObject;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Controller
public class ArticleApi {
    /**
     * 作用：文章CRUD中的Create。
     *
     * @param request: HttpServletRequest
     */
    @PostMapping("/api/createfiction")
    public ResponseEntity<?> createFiction(HttpServletRequest request) {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String createTime = now.format(formatter);

        JSONObject failedJo = new JSONObject();
        failedJo.put("result", 404);
        failedJo.put("createtime", createTime);

        String uuid = RequestHelper.getUserUUIDFromRequest(request);
        if (uuid == null || uuid.isEmpty()) {
            failedJo.put("description", "当前用户证明是空的");
            return ResponseEntity.ok(failedJo.toString());
        }

        if (!AccountHelper.isAdminFromUUID(uuid)) {
            failedJo.put("description", "当前用户没有权限");
            return ResponseEntity.ok(failedJo.toString());
        }

        Map<String, String[]> map = request.getParameterMap();
        if (map.containsKey("title") &&
                map.containsKey("description") &&
                map.containsKey("rootcatlog") &&
                map.containsKey("catlog") &&
                map.containsKey("author") &&
                map.containsKey("finishyear") &&
                map.containsKey("finished")) {

            String title = map.get("title")[0].trim();
            String description = map.get("description")[0].trim();
            String rootcatlog = map.get("rootcatlog")[0];
            String catlog = map.get("catlog")[0];
            String author = map.get("author")[0].trim();
            String authorId = AuthorHelper.getId(author);
            String strFinished = map.get("finished")[0];
            boolean finished = strFinished.equals("true") ? true : false;
            if (authorId == null) {
                return ResponseEntity.ok(ResponseHelper.createBasicJsonObject(404, "找不到拥有名字为 " + author + " 的作者").toString());
            }
            else {

                String finishyear = map.get("finishyear")[0].trim();

                MongoCollection<Document> collection = DatabaseMan.Instance().GetCollection(GlobalConfig.collectionNameOfArticle);

                // author and book name both equal = same book
                boolean fictionExist = false;
                AggregateIterable<Document> documents = collection.aggregate(Arrays.asList(
                        new Document("$match", new Document("title", title)),
                        new Document("$match", new Document("author", authorId))
                ));

                MongoCursor<Document> cursor = documents.cursor();
                if (cursor.hasNext()) {
                    fictionExist = true;
                }
                cursor.close();

                if (title.isEmpty()) {
                    failedJo.put("description", "书名不能为空");
                } else if (rootcatlog.isEmpty()) {
                    failedJo.put("description", "分类不能为空");
                } else if (catlog.isEmpty()) {
                    failedJo.put("description", "子分类不能为空");
                } else if (authorId.isEmpty()) {
                    failedJo.put("description", "作者ID不能为空");
                } else if (description.length() < 30) {
                    failedJo.put("description", "描述不能小于30个字");
                } else if (fictionExist) {
                    failedJo.put("description", "该小说已经存在");
                } else if (finished && (finishyear == null || finishyear.isEmpty() || finishyear.length() != 4 || !StringHelper.isAllCharacterDigit(finishyear))) {
                    failedJo.put("description", "完本年份填写不正确");
                } else {
                    String remoteIp = NetworkHelper.getIPAddress(request);
                    description = StringHelper.replaceReturnWithBR(description);

                    String pinyin = HanYu.Instance().getStringPinYin(title);

                    //文章加入
                    Document document = new Document("title", title)
                            .append("pinyin", pinyin)
                            .append("description", description)
                            .append("rootcatlog", rootcatlog)
                            .append("catlog", catlog)
                            .append("author", authorId)
                            .append("score", 6.9)
                            .append("createtime", createTime)
                            .append("finishyear", finishyear)
                            .append("finished", finished)
                            .append("promoted", false)
                            .append("fromip", remoteIp)
                            .append("scoredcount", (long)0);

                    collection.insertOne(document);

                    //第一个默认的分数加入
                    ScoreHelper.submitScore(uuid, document.get("_id").toString(), 6.9f);

                    JSONObject jo = ResponseHelper.createBasicJsonObject(200, "ok");
                    jo.put("createtime", createTime);
                    return ResponseEntity.ok(jo.toString());
                }
            }
        }

        return ResponseEntity.ok(failedJo.toString());
    }

    /**
     * 作用：更新文章的相关信息（暂时不支持分类更新）
     * @param request
     * @return
     */
    @PostMapping("/api/updatefiction")
    public ResponseEntity<?> updateOneFiction(HttpServletRequest request) {
        String title = null, author = null, description = null, finishyear = null, fictionid = null,  strFinished = null;
        Map<String, String[]> map = request.getParameterMap();
        if (map.containsKey("title")) {
            title = map.get("title")[0].trim();
        }
        if (map.containsKey("author")) {
            author = map.get("author")[0].trim();
        }
        if (map.containsKey("description")) {
            description = map.get("description")[0].trim();
        }
        if (map.containsKey("finishyear")) {
            finishyear = map.get("finishyear")[0].trim();
        }
        if (map.containsKey("fictionid")) {
            fictionid = map.get("fictionid")[0].trim();
        }
        if (map.containsKey("finished")) {
            strFinished = map.get("finished")[0].trim();
        }

        boolean finished = false;

        if (strFinished != null && strFinished.equals("true")) {
            finished = true;
        }

        String result;
        if (title == null || title.isEmpty()) {
            result = ResponseHelper.createBasicJsonObject(404, "题目不能为空").toString();
        }
        else if(author == null || author.isEmpty()) {
            result = ResponseHelper.createBasicJsonObject(404, "作者不能为空").toString();
        }
        else if (finished && (finishyear == null || finishyear.isEmpty())) {
            result = ResponseHelper.createBasicJsonObject(404, "完本年代不能为空").toString();
        }
        else if (fictionid == null || fictionid.isEmpty()) {
            result = ResponseHelper.createBasicJsonObject(404, "没有有效的文章ID").toString();
        }
        else if (description == null || description.length() < 30) {
            result = ResponseHelper.createBasicJsonObject(404, "描述内容不能为空").toString();
        }
        else {
            ArticleHelper.updateArticle(fictionid, title, author, description, finishyear, finished);
            String time = TimeHelper.getFormattedNowString();
            JSONObject jo = ResponseHelper.createBasicJsonObject(200, "ok");
            jo.put("createtime", time);
            result = jo.toString();
        }

        return ResponseEntity.ok(result);
    }

    /**
     * 作用：文章CRUD中的Delete。
     *
     * @param request: HttpServletRequest
     */
    @PostMapping("/api/deletefiction")
    public ResponseEntity<?> deleteOneFiction(HttpServletRequest request) {
        String uuid = RequestHelper.getUserUUIDFromRequest(request);
        boolean isAdmin = AccountHelper.isAdminFromUUID(uuid);

        if (isAdmin) {
            Map<String, String[]> map = request.getParameterMap();
            if (map.containsKey("cid")) {
                String value = map.get("cid")[0];
                MongoCollection<Document> collection = DatabaseMan.Instance().GetCollection(GlobalConfig.collectionNameOfArticle);

                Bson condition = new Document("$eq", new ObjectId(value));
                Bson filter = new Document("_id", condition);
                DeleteResult result = collection.deleteOne(filter);

                if (result.getDeletedCount() == 1) {
                    JSONObject jo = new JSONObject();
                    jo.put("result", 200);

                    return ResponseEntity.ok(jo.toString());
                }
            }
        }

        JSONObject jo = new JSONObject();
        jo.put("result", 404);
        return ResponseEntity.badRequest().body(jo.toString());
    }

    @PostMapping("/api/commentthumb")
    public ResponseEntity<?> commentThumbup(HttpServletRequest request) {
        String uuid = RequestHelper.getUserUUIDFromRequest(request);
        boolean isLogin = AccountHelper.isExistFromUUID(uuid);

        String result;
        if (isLogin) {
            Map<String, String[]> map = request.getParameterMap();
            String commentId = null, gesture = null;
            if (map.containsKey("commentid")) {
                commentId = map.get("commentid")[0];
            }
            if (map.containsKey("gesture")) {
                gesture = map.get("gesture")[0];
            }

            if (commentId == null && commentId.isEmpty()) {
                result = ResponseHelper.createBasicJsonObject(404, "点赞的目标（ID）没有提供").toString();
            }
            else if (gesture == null && gesture.isEmpty()) {
                result = ResponseHelper.createBasicJsonObject(404, "姿势不对").toString();
            }
            else {
                CommentThumbHelper.commentThumb(uuid, commentId, gesture);
                long thumbdownCount = CommentThumbHelper.getCommentThumbdownCount(commentId);
                long thumbupCount = CommentThumbHelper.getCommentThumbupCount(commentId);
                JSONObject jo = ResponseHelper.createBasicJsonObject(200, "ok");
                jo.put("thumbdown", String.valueOf(thumbdownCount));
                jo.put("thumbup", String.valueOf(thumbupCount));
                result = jo.toString();
            }
        }
        else {
            result = ResponseHelper.createBasicJsonObject(404, "登录后才能点赞").toString();
        }

        return ResponseEntity.ok(result);
    }

    @PostMapping("/api/getarticlefrompinyin")
    public ResponseEntity<?> getArticleFromPinYin(HttpServletRequest request) {
        String result;

        String alphabet = "a";
        Map<String, String[]> map = request.getParameterMap();
        if (map.containsKey("key")) {
            String key = map.get("key")[0];
            if (key != null && !key.trim().equals("")) {
                alphabet = key;
            }
        }

        List<String[]> resultList = ArticleHelper.findArticleFromPinYin(alphabet);

        JSONObject jo = ResponseHelper.createBasicJsonObject(200, "ok");
        jo.put("list", resultList);
        result = jo.toString();
        return ResponseEntity.ok(result);
    }
}
